const { Service } = require('egg');
const { v4: uuidV4 } = require('uuid');
const moment = require('moment');
const order_table = 'order_info',
  product_table = 'product',
  order_product_table = 'order_product';


class ProductService extends Service {

  async insertInstance(order_id, products) {
    const ctx = this.ctx;
    try {
      const { id: user_id } = ctx.session;
      const instances = [];
      const time = moment();
      for (const p of products) {
        const obj = {
          uuid: uuidV4(),
          product_id: p.product_id,
          number: p.number,
          order_id,
          create_time: moment(time).format('YYYY-MM-DD HH:mm:ss'),
          update_time: moment(time).format('YYYY-MM-DD HH:mm:ss'),
          create_by: user_id,
          update_by: user_id,
          is_delete: 0,
        };

        instances.push(obj);
      }


      return instances;
    } catch (error) {
      throw error;
    }
  }

  async product(uuid, order, method, pageIndex, pageSize) {
    const ctx = this.ctx;
    try {
      const list = await ctx.app.knex().select('t2.uuid', 't2.name as order_name', 't3.name as product_name', 't1.number')
        .from(`${order_product_table} as t1`)
        .leftJoin(`${order_table} as t2`, function() {
          this.on('t1.order_id', '=', 't2.uuid');
        })
        .leftJoin(`${product_table} as t3`, function() {
          this.on('t3.uuid', '=', 't1.product_id');
        })
        .where('t1.is_delete', 0)
        .andWhere('t1.order_id', uuid)
        .orderBy(`t1.${order}`, method)
        .limit(Number(pageSize))
        .offset((Number(pageIndex) - 1) * Number(pageSize));

      const count = await ctx.app.knex().count('t1.uuid as count')
        .from(`${order_product_table} as t1`)
        .where('t1.is_delete', 0)
        .andWhere('t1.order_id', uuid)
        .first();

      const result = {
        list,
        count: count.count,
      };

      return result;
    } catch (error) {
      throw error;
    }
  }


  async orderInventory(product) {
    const ctx = this.ctx;
    const time = moment();
    const { id: user_id } = ctx.session;
    try {
      const instances = [];

      for (const p of product) {
        const obj = {
          uuid: uuidV4(),
          product_id: p.product_id,
          number: p.number,
          type: 3,
          create_time: moment(time).format('YYYY-MM-DD HH:mm:ss'),
          update_time: moment(time).format('YYYY-MM-DD HH:mm:ss'),
          create_by: user_id,
          update_by: user_id,
        };

        instances.push(obj);
      }

      // await trx(inventory_table).insert(instances);

      return instances;
    } catch (error) {
      throw error;
    }
  }

}


module.exports = ProductService;
